
//@version=5
indicator("THV Coral FILTER", shorttitle="THV Coral FILTER", overlay=true)

// Inputs
gi_80 = input.bool(true, title="Use Coral")
gi_84 = input.int(4, title="Period", minval=1)
gd_88 = input.float(0.5, title="Multiplier", step=0.1)

// Calculation function
calculation() =>
    var float gd_136 = -gd_88 * gd_88 * gd_88
    var float gd_144 = 3.0 * (gd_88 * gd_88 + gd_88 * gd_88 * gd_88)
    var float gd_152 = -3.0 * (2.0 * gd_88 * gd_88 + gd_88 + gd_88 * gd_88 * gd_88)
    var float gd_160 = 3.0 * gd_88 + 1.0 + gd_88 * gd_88 * gd_88 + 3.0 * gd_88 * gd_88
    var float gd_168 = gi_84 < 1 ? 1 : (gi_84 - 1.0) / 2.0 + 1.0
    var float gd_176 = 2.0 / (gd_168 + 1.0)
    var float gd_184 = 1.0 - gd_176

    [gd_136, gd_144, gd_152, gd_160, gd_168, gd_176, gd_184]

// Assign global variables using the calculation function
[gd_136, gd_144, gd_152, gd_160, gd_168, gd_176, gd_184] = calculation()

// Calculate THV Coral values
gda_112 = ta.sma(close, gi_84)
gda_116 = ta.sma(gda_112, gi_84)
gda_120 = ta.sma(gda_116, gi_84)
gda_124 = ta.sma(gda_120, gi_84)
gda_128 = ta.sma(gda_124, gi_84)
gda_132 = ta.sma(gda_128, gi_84)

g_ibuf_108 = gd_136 * gda_132 + gd_144 * gda_128 + gd_152 * gda_124 + gd_160 * gda_120

// Colors for plot
upColor = color.rgb(9, 243, 16)
downColor = color.rgb(248, 7, 7)

// Determine the relationship between current and previous Coral values
var float g_ibuf_96 = na
var float g_ibuf_100 = na
var float g_ibuf_104 = na
var float prevCoralValue = na

if gi_80
    for i = 1 to ta.barssince(not na(g_ibuf_108)) - 1
        if not na(g_ibuf_108[i])
            prevCoralValue := g_ibuf_108[i]
            break

    if not na(prevCoralValue)
        if prevCoralValue > g_ibuf_108[1]
            g_ibuf_100 := g_ibuf_108
            g_ibuf_104 := na
        else if prevCoralValue < g_ibuf_108[1]
            g_ibuf_104 := g_ibuf_108
            g_ibuf_100 := na
        else
            g_ibuf_100 := na
            g_ibuf_104 := na

// Plot THV Coral values with conditional colors
plot(g_ibuf_108, title="THV Coral", color=g_ibuf_108 > g_ibuf_108[1] ? upColor : downColor, linewidth=2)
plot(g_ibuf_100, color=color.new(upColor, 0), style=plot.style_stepline)
plot(g_ibuf_104, color=color.new(downColor, 0), style=plot.style_stepline)